package org.komarichin.struts2.actions.article;

import org.apache.commons.lang.StringUtils;
import org.komarichin.Constants;
import org.komarichin.beans.IArticle;
import org.komarichin.beans.IComment;
import org.komarichin.beans.IHasComment;
import org.komarichin.beans.ILanguage;
import org.komarichin.feed.IEntryFeed;
import org.komarichin.feed.IFeedWriter;
import org.komarichin.struts2.BaseAction;
import org.komarichin.struts2.beans.SeoBlank;
import org.komarichin.struts2.beans.models.PageModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * &nbsp;
 * </p>
 * User: Michael Komarichin
 * Date: Jan 23, 2010
 * Time: 11:45:49 PM
 */
public class ArticleAction extends BaseAction {
    private static final long serialVersionUID = 7413819295683483408L;
    private static final Logger log = LoggerFactory.getLogger(ArticleAction.class);


    private PageModel page = new PageModel();

    @Autowired
    private IArticle<Long> article;
    @Autowired
    private IComment<String> comment;

    @Override
    public String getFeed() throws Exception {
        String basePath = getConfigurator().getServerBasePath();
        List<IEntryFeed> l = new ArrayList<IEntryFeed>();
        for (IArticle<Long> n : getLatestArticles()) {
            if (n != null) {
                n.setLink(basePath + "/article/view?article.id=" + n.getId());
                l.add(n);
            }
        }
        String result;
        if (IFeedWriter.FEED_TYPE_RSS.equals(getFeedType())) {
            result = getFeedWriter().getFeeds("Articles", "/article/archive", "latest articles", "rss_2.0", l);
        } else {
            result = getFeedWriter().getFeeds("Articles", "/article/archive", "latest articles", "atom_0.3", l);
        }
        return result;
    }


    /**
     * from parameters passed  object IArticle without identifier, create news
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if created news
     */
    public String save() {
        log.debug("save: {}", article);
        article = getArticleService().save(article);
        if (article != null && article.getId() != null) {
            addActionMessage(getText("article.message.create.success"));
        } else {
            addActionError(getText("article.error.article.not.created"));
        }
        return SUCCESS;
    }

    /**
     * update article. take old article identifier and new value of fields Iarticle's object in request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if updated article
     */
    public String update() {
        log.debug("update: {}", article);
        getArticleService().saveOrUpdate(article);
        return SUCCESS;
    }

    /**
     * get article by identifier, it will passed in request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if article was loaded or {@code com.opensymphony.xwork2.Action.INPUT} if article's identifier is null
     */
    public String load() {
        log.debug("loading article# {}", article);
        if (article != null && article.getId() != null) {
            this.article = getArticleService().findById(article.getId());
            defineMetaTags(this.article);

            return SUCCESS;
        } else {
            log.warn("user not choice article id");
            addActionError(getText("article.error.not.choice.article"));
            return INPUT;
        }
    }

    /**
     * delete article. take  article's  identifier  from  request parameters
     *
     * @return {@code com.opensymphony.xwork2.Action.SUCCESS} if delete article or {@code com.opensymphony.xwork2.Action.INPUT} if article's identifier is null
     */
    public String delete() {
        log.debug("delete: {}", article);
        if (article != null && article.getId() != null) {
            getArticleService().remove(article.getId());
            addActionMessage(getText("article.message.article.removed.success"));
            return SUCCESS;
        } else {
            log.warn("user not choice article id");
            addActionError(getText("article.error.not.choice.article"));
            return INPUT;
        }
    }

    public Collection<IArticle<Long>> getArticleList() {
        log.debug("get article list#page: " + page);
        defineMetaTags(new SeoBlank(getText("article.list.title"),
                getText("article.list.description"),
                getText("article.list.keyWords"), new Date()));
        if (StringUtils.isNotEmpty(getUserLanguage())) {
            ILanguage<Long> lang = getLanguageService().findByName(getUserLanguage());
            if (lang != null) {
                return getArticleService().getArticles(lang, page.getStart(), page.getLimit(), page.getField(), page.isOrder());
            }
        }
        return getArticleService().getArticles(page.getStart(), page.getLimit(), page.getField(), page.isOrder());
    }

    public Collection<IArticle<Long>> getLatestArticles() {
        log.debug("get latest article");
        defineMetaTags(new SeoBlank(getText("article.latest.title"),
                getText("article.latest.description"),
                getText("article.latest.keyWords"), new Date()));

        if (StringUtils.isNotEmpty(getUserLanguage())) {
            ILanguage<Long> lang = getLanguageService().findByName(getUserLanguage());
            if (lang != null) {
                return getArticleService().getLatestArticles(lang);
            }
        }

        return getArticleService().getLatestArticles();
    }

    public IArticle<Long> getArticle() {
        return article;
    }


    public Collection<PageModel> getPages() {
        Collection<PageModel> result = new ArrayList<PageModel>();
        int count = 0;
                int limit = page.getLimit();
        if(limit == 0) limit = Constants.DISPLAY_LIMIT;
        count = getNewsService().getCountNews();
        int tt = (int) Math.abs(Math.ceil((double) count / limit));
        for (int t = 0; t < tt; t++) {
            PageModel p = new PageModel();
            p.setName(String.valueOf(t + 1));
            p.setStart(t * limit);
            p.setLimit(limit);
            p.setField(page.getField());
            p.setOrder(page.isOrder());
            result.add(p);
        }
        return result;
    }    

    public Collection<IArticle<Long>> getAllArticles() {
        return getArticleService().getAll();
    }

    public String addComment() {
        getCommentService().assignCommentToObject((IHasComment) article, comment);
        return SUCCESS;
    }

    public IComment<String> getComment() {
        return comment;
    }

    public void setComment(IComment<String> comment) {
        this.comment = comment;
    }

    public String getCountArticles() {
        int result = 0;
        result = getArticleService().getCountArticles();
        if (result == 1000) {
            return ">= 1000";
        }
        return String.valueOf(result);
    }

    public int getCurrentPage() {

        if (page.getLimit() == 0) {
            return 0;
        }

        int countNews = getArticleService().getCountArticles();
        int countPages = countNews / page.getLimit();


        return 0;
    }

    public String getCountPagesArticles() {
        int result = 0;
        result = getArticleService().getCountArticles();
        if (result == 1000) {
            return ">= 1000";
        }
        return String.valueOf(result);
    }

    public PageModel getPage() {
        return page;
    }

    public void setPage(PageModel page) {
        this.page = page;
    }

}
